# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-07-15 23:28
# File     : advanced_analysis.py
# Project  : dynamic-portfolio-optimizer
# Desc     : 高级分析示例
# examples/advanced_analysis.py
"""
高级数据分析示例
"""

import sys
from pathlib import Path
import pandas as pd
import numpy as np
from datetime import datetime, timedelta

# 添加项目路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from src.services.market_data_service import MarketDataService


class TechnicalAnalyzer:
    """技术分析器"""

    @staticmethod
    def add_technical_indicators(df: pd.DataFrame) -> pd.DataFrame:
        """添加技术指标"""
        df = df.copy()

        # 移动平均线
        df['MA5'] = df['close'].rolling(5).mean()
        df['MA20'] = df['close'].rolling(20).mean()
        df['MA50'] = df['close'].rolling(50).mean()

        # 布林带
        df['BB_middle'] = df['close'].rolling(20).mean()
        bb_std = df['close'].rolling(20).std()
        df['BB_upper'] = df['BB_middle'] + (bb_std * 2)
        df['BB_lower'] = df['BB_middle'] - (bb_std * 2)

        # RSI
        delta = df['close'].diff()
        gain = delta.where(delta > 0, 0)
        loss = -delta.where(delta < 0, 0)
        avg_gain = gain.rolling(14).mean()
        avg_loss = loss.rolling(14).mean()
        rs = avg_gain / avg_loss
        df['RSI'] = 100 - (100 / (1 + rs))

        # MACD
        ema12 = df['close'].ewm(span=12).mean()
        ema26 = df['close'].ewm(span=26).mean()
        df['MACD'] = ema12 - ema26
        df['MACD_signal'] = df['MACD'].ewm(span=9).mean()
        df['MACD_histogram'] = df['MACD'] - df['MACD_signal']

        # 波动率
        df['volatility'] = df['close'].pct_change().rolling(20).std() * np.sqrt(252) * 100

        return df

    @staticmethod
    def generate_signals(df: pd.DataFrame) -> pd.DataFrame:
        """生成交易信号"""
        df = df.copy()

        # 初始化信号列
        df['signal'] = 0
        df['signal_type'] = ''

        # MA交叉信号
        ma_cross_buy = (df['MA5'] > df['MA20']) & (df['MA5'].shift(1) <= df['MA20'].shift(1))
        ma_cross_sell = (df['MA5'] < df['MA20']) & (df['MA5'].shift(1) >= df['MA20'].shift(1))

        # RSI超买超卖信号
        rsi_oversold = df['RSI'] < 30
        rsi_overbought = df['RSI'] > 70

        # 布林带信号
        bb_buy = df['close'] < df['BB_lower']
        bb_sell = df['close'] > df['BB_upper']

        # 综合信号
        buy_signals = ma_cross_buy | (rsi_oversold & bb_buy)
        sell_signals = ma_cross_sell | (rsi_overbought & bb_sell)

        df.loc[buy_signals, 'signal'] = 1
        df.loc[buy_signals, 'signal_type'] = 'BUY'
        df.loc[sell_signals, 'signal'] = -1
        df.loc[sell_signals, 'signal_type'] = 'SELL'

        return df


def portfolio_analysis():
    """投资组合分析示例"""

    print("📊 开始投资组合分析...")

    market_service = MarketDataService()

    # 定义投资组合
    portfolio = {
        'AAPL': 0.3,  # 30%
        'GOOGL': 0.25,  # 25%
        'MSFT': 0.2,  # 20%
        'TSLA': 0.15,  # 15%
        'NVDA': 0.1  # 10%
    }

    # 获取历史数据
    start_date = datetime.now() - timedelta(days=365)
    end_date = datetime.now()

    print("📈 获取组合股票数据...")
    portfolio_data = market_service.get_stock_price(
        symbols=list(portfolio.keys()),
        start_date=start_date,
        end_date=end_date,
        interval='1d'
    )

    # 计算组合表现
    portfolio_returns = pd.DataFrame()

    for symbol, weight in portfolio.items():
        if symbol in portfolio_data and not portfolio_data[symbol].empty:
            returns = portfolio_data[symbol]['close'].pct_change()
            portfolio_returns[symbol] = returns * weight

    if not portfolio_returns.empty:
        # 组合总收益
        portfolio_returns['total'] = portfolio_returns.sum(axis=1)

        # 计算关键指标
        total_return = (1 + portfolio_returns['total']).prod() - 1
        annual_return = (1 + portfolio_returns['total'].mean()) ** 252 - 1
        volatility = portfolio_returns['total'].std() * np.sqrt(252)
        sharpe_ratio = annual_return / volatility if volatility > 0 else 0

        # 最大回撤
        cumulative = (1 + portfolio_returns['total']).cumprod()
        max_drawdown = (cumulative / cumulative.expanding().max() - 1).min()

        print(f"\n📈 投资组合表现分析:")
        print(f"   总收益率: {total_return:.2%}")
        print(f"   年化收益率: {annual_return:.2%}")
        print(f"   年化波动率: {volatility:.2%}")
        print(f"   夏普比率: {sharpe_ratio:.3f}")
        print(f"   最大回撤: {max_drawdown:.2%}")

        # 个股贡献度分析
        print(f"\n🎯 个股收益贡献:")
        for symbol in portfolio.keys():
            if symbol in portfolio_returns.columns:
                stock_contribution = portfolio_returns[symbol].sum()
                print(f"   {symbol}: {stock_contribution:.2%}")


def technical_analysis_example():
    """技术分析示例"""

    print("\n🔍 技术分析示例...")

    market_service = MarketDataService()
    analyzer = TechnicalAnalyzer()

    # 获取数据
    symbol = 'AAPL'
    start_date = datetime.now() - timedelta(days=200)
    end_date = datetime.now()

    data = market_service.get_stock_price(
        symbols=symbol,
        start_date=start_date,
        end_date=end_date,
        interval='1d'
    )

    if not data.empty:
        # 添加技术指标
        data_with_indicators = analyzer.add_technical_indicators(data)

        # 生成交易信号
        data_with_signals = analyzer.generate_signals(data_with_indicators)

        # 最新数据分析
        latest = data_with_signals.iloc[-1]

        print(f"\n📊 {symbol} 最新技术分析:")
        print(f"   当前价格: ${latest['close']:.2f}")
        print(f"   5日均线: ${latest['MA5']:.2f}")
        print(f"   20日均线: ${latest['MA20']:.2f}")
        print(f"   RSI: {latest['RSI']:.1f}")
        print(f"   MACD: {latest['MACD']:.3f}")
        print(f"   波动率: {latest['volatility']:.1f}%")

        # 最近的交易信号
        recent_signals = data_with_signals[data_with_signals['signal'] != 0].tail(3)
        if not recent_signals.empty:
            print(f"\n🎯 最近交易信号:")
            for idx, row in recent_signals.iterrows():
                print(f"   {idx.strftime('%Y-%m-%d')}: {row['signal_type']} @ ${row['close']:.2f}")


def correlation_analysis():
    """相关性分析示例"""

    print("\n📊 股票相关性分析...")

    market_service = MarketDataService()

    # 科技股篮子
    tech_stocks = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'NVDA', 'META', 'AMZN']

    start_date = datetime.now() - timedelta(days=365)
    end_date = datetime.now()

    # 获取数据
    stock_data = market_service.get_stock_price(
        symbols=tech_stocks,
        start_date=start_date,
        end_date=end_date,
        interval='1d'
    )

    # 构建价格矩阵
    prices = pd.DataFrame()
    for symbol, data in stock_data.items():
        if not data.empty:
            prices[symbol] = data['close']

    if not prices.empty:
        # 计算收益率
        returns = prices.pct_change().dropna()

        # 相关性矩阵
        correlation_matrix = returns.corr()

        print(f"\n📈 相关性分析结果:")
        print("相关性矩阵 (前5x5):")
        print(correlation_matrix.iloc[:5, :5].round(3))

        # 找出高相关性股票对
        print(f"\n🔗 高相关性股票对 (>0.7):")
        for i in range(len(correlation_matrix.columns)):
            for j in range(i + 1, len(correlation_matrix.columns)):
                corr = correlation_matrix.iloc[i, j]
                if corr > 0.7:
                    stock1 = correlation_matrix.columns[i]
                    stock2 = correlation_matrix.columns[j]
                    print(f"   {stock1} - {stock2}: {corr:.3f}")


if __name__ == "__main__":
    try:
        portfolio_analysis()
        technical_analysis_example()
        correlation_analysis()

        print("\n✅ 高级分析完成!")

    except Exception as e:
        print(f"❌ 分析过程中出现错误: {e}")

